<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/12
 * Time: 19:33
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */


namespace app\home\controller;


use app\common\model\CircleComment;
use app\common\model\CircleCommentLike;
use app\common\model\CircleLike;
use app\common\model\Config;
use app\common\model\FollowUser;
use app\common\model\Level;
use app\common\model\MessageTemplate;
use app\common\model\NoticeMessage;
use app\Request;
use think\Exception;

class Circle
{

    public function addCircle(Request $request)
    {
        $param = $request->param();
        $circleModel = new \app\common\model\Circle();
        if ($request->userInfo['level_id'] > 1) {
            $circle_number = Config::getConfigValue('level_circle_number');
        } else {
            $circle_number = Config::getConfigValue('circle_number');
        }
        if ($circle_number >= 0) {
            $todayCircleCount = $circleModel->where('create_time', strtotime(date('Y-m-d 00:00:00')))
                ->where('uid', '=', $request->userInfo['id'])
                ->count();
            if ($circle_number <= $todayCircleCount) {
                return error('今日发布数量已达上限');
            }
        }
        $data = [
            'uid' => $request->userInfo['id'],
            'title' => $param['title'],
            'img' => $param['img'],
            'notice_user' => $param['notice_user'],
            'authority' => $param['authority'],
            'create_time' => time(),
            'address' => $param['address'],
        ];
        if (isset( $param['longitude']) && !empty( $param['longitude'])  && isset( $param['dimension']) && !empty( $param['dimension'])){
            $data['longitude'] = $param['longitude'];
            $data['dimension'] = $param['dimension'];
            $longitude = number_format(doubleval($data['longitude']), 6);
            $latitude = number_format(doubleval($data['dimension']), 6);
            $gps = $latitude . ',' . $longitude;
            $params = array(
                'location' => $gps,
                'key' => Config::getConfigValue('tencent_map_key'),
            );
            $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
            $url = $url . '?' . http_build_query($params, '', '&');
            $mapResult = json_decode(curlGet($url));
            if ($mapResult->status == 0) {
                /* return error('百度地图数据获取有误')*/
                $data['province_name'] = $mapResult->result->address_component->province;
                $data['city_name'] = $mapResult->result->address_component->city;
                $data['area_name'] = $mapResult->result->address_component->district;
                /*  $user['address'] = $mapResult->result->address;*/
                // $data['address'] = $mapResult['address'];
            };

        }
        $isAuditing = Config::getConfigValue('circle_status');
        if ($isAuditing == 1) {
            $data['status'] = '1';
        } else {
            $data['status'] = '2';
        }
        $circleModel->insert($data);
        if ($isAuditing != 1) {
            $messageModel = new MessageTemplate();
            $xcxMessage[0]['data'] = [
                'thing1' => ['value' => '动态'],
                'thing2' => ['value' => $data['title']],
                'phrase3' => ['value' => '通过'],
                'time5' => ['value' => date('Y-m-d H:i:s')],
            ];
            $xcxMessage[0]['uid'] = [$request->userInfo['id']];
            $xcxMessage[0]['title'] = 'release';
            $messageModel->sendMessage(3, $xcxMessage);
            $gzhMessage[0]['data'] = [
                'thing10' => ['value' => '动态'],
                'thing28' => ['value' => $request->userInfo['nickname']],
                'thing9' => ['value' => $data['title']],
                'thing2' => ['value' => '通过'],
            ];
            $gzhMessage[0]['uid'] = $request->userInfo['id'];
            $gzhMessage[0]['title'] = 'release';
            $messageModel->sendMessage(1, $gzhMessage);

        }
        return success('发布成功');

    }
    public function updateCircle(Request $request)
    {
        $param = $request->param();
        $data = [
            'uid' => $request->userInfo['id'],
            'title' => $param['title'],
            'img' => $param['img'],
            'notice_user' => $param['notice_user'],
            'authority' => $param['authority'],
            'create_time' => time(),
            'address' => $param['address'],
        ];
        if (isset( $param['longitude']) && !empty( $param['longitude'])  && isset( $param['dimension']) && !empty( $param['dimension'])){
            $data['longitude'] = $param['longitude'];
            $data['dimension'] = $param['dimension'];
            $longitude = number_format(doubleval($data['longitude']), 6);
            $latitude = number_format(doubleval($data['dimension']), 6);
            $gps = $latitude . ',' . $longitude;
            $params = array(
                'location' => $gps,
                'key' => Config::getConfigValue('tencent_map_key'),
            );
            $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
            $url = $url . '?' . http_build_query($params, '', '&');
            $mapResult = json_decode(curlGet($url));
            if ($mapResult->status == 0) {
                /* return error('百度地图数据获取有误')*/
                $data['province_name'] = $mapResult->result->address_component->province;
                $data['city_name'] = $mapResult->result->address_component->city;
                $data['area_name'] = $mapResult->result->address_component->district;
                /*  $user['address'] = $mapResult->result->address;*/
                // $data['address'] = $mapResult['address'];
            };

        }
        $circleModel = new \app\common\model\Circle();

        $isAuditing = Config::getConfigValue('circle_status');
        if ($isAuditing == 1) {
            $data['status'] = '1';
        } else {
            $data['status'] = '2';
        }
        $circleModel->where(['id' => $param['id']])->update($data);
        return success('发布成功');

    }
    public function circleList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['c.status', '<>', 4];
        if (isset($param['is_oneself_uid']) && !empty($param['is_oneself_uid'])) {
            $where[] = ['c.uid', '=', $param['is_oneself_uid']];
        } else {
            $where[] = ['c.status', '=', 2];
        }


        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['c.uid', '=', $param['uid']];
            $where[] = ['c.status', '=', 2];
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['c.status', '=', $param['status']];
        }
        $circleModel = new \app\common\model\Circle();
        $userModel = new \app\common\model\User();
        if (isset($param['dimension']) && !empty($param['dimension']) &&
            isset($param['longitude']) && !empty($param['longitude'])){
            $dimension = $param['dimension'];
            $longitude = $param['longitude'];
        }else{
            $dimension =  Config::getConfigValue('dimension') ;
            $longitude =  Config::getConfigValue('longitude') ;
        }
        if (empty($dimension)){
            $dimension = '39.54';
        }
        if (empty($longitude)){
            $longitude = '116.23';
        }
        $sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$dimension}
         * PI() / 180 - c.dimension * PI() / 180) / 2), 2) + COS({$dimension} * PI() / 180)
          * COS(c.dimension * PI() / 180) * POW(SIN(({$longitude} * PI() / 180 - c.longitude * PI() / 180) / 2), 2))) 
          * 1000) AS distance";
        if (isset($param['circle_sort_rule']) && $param['circle_sort_rule'] == 1){
            $orderField = 'distance';
            $orderType = 'asc';
        }else{
            $orderField = 'c.create_time';
            $orderType = 'desc';
        }
        $list = $circleModel->alias('c')
            ->leftJoin('user u', 'c.uid  = u.id')
            ->field('c.*,u.nickname,u.avatar,'.$sql)
            ->order($orderField, $orderType)
            ->where($where)
            ->limit($start, $limit)
            ->select()->toArray();
        $circleLikeModel = new CircleLike();
        $followUserModel = new FollowUser();
        foreach ($list as $key => $value) {
            if (isset($param['oneself_uid']) && !empty($param['oneself_uid'])) {
                $is_follow = $followUserModel
                    ->where([
                        'uid' =>$param['oneself_uid'],
                        'follow_uid' => $value['uid']])
                    ->find();
                if ($is_follow) {
                    $list[$key]['is_follow'] = 1;
                } else {
                    $list[$key]['is_follow'] = 0;
                }
                $like = $circleLikeModel->where(['circle_id' => $value['id'], 'uid' => $param['oneself_uid']])->find();

                if ($like) {
                    $list[$key]['is_like'] = 1;
                } else {
                    $list[$key]['is_like'] = 0;
                }
                if ($value['notice_user']) {
                    $list[$key]['notice_user_list'] = $userModel->where('id', 'in', $value['notice_user'])->field('id,nickname')->select()->toArray();
                } else {
                    $list[$key]['notice_user_list'] = [];
                }

            }else{
                $list[$key]['is_follow'] = 0;
                $list[$key]['is_like'] = 0;
                $list[$key]['notice_user_list'] = [];
            }
            $list[$key]['distance_kilometer']  =  haversineDistance($dimension,$longitude,$value['dimension'],$value['longitude']);

        }
        $count = $circleModel->alias('c')
            ->leftJoin('user u', 'c.uid  = u.id')
            ->limit($start, $limit)
            ->count();
        return success('成功', ['list' => $list, 'count' => $count]);
    }

    public function circleInfo(Request $request)
    {
        $param = $request->param();
        $circleModel = new \app\common\model\Circle();
        $info = $circleModel->alias('c')
            ->where(['c.id' => $param['id']])
            ->leftJoin('user u', 'c.uid  = u.id')
            ->field('c.*,u.nickname,u.avatar,u.id as userid')
            ->find();
        $userModel = new \app\common\model\User();
        if ($info['notice_user']) {
            $info['notice_user_list'] = $userModel->where('id', 'in', $info['notice_user'])->field('id,nickname,avatar')->select()->toArray();
        } else {
            $info['notice_user_list'] = [];
        }
        $followUserModel = new FollowUser();
        $is_follow = $followUserModel->where(['uid' => $request->userInfo['id'], 'follow_uid' => $info['userid']])->find();
        if ($is_follow) {
            $info['is_follow'] = 1;
        } else {
            $info['is_follow'] = 0;
        }
        $circleLikeModel = new CircleLike();
        $like = $circleLikeModel->where(['circle_id' => $info['id'], 'uid' => $request->userInfo['id']])->find();
        if ($like) {
            $info['is_like'] = 1;
        } else {
            $info['is_like'] = 0;
        }
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $circleCommentModel = new CircleComment();
        $circleCommentList = $circleCommentModel->where(['circle_id' => $info['id'], 'pid' => 0])
            ->limit($start, $limit)->select()->toArray();
        $count = $circleCommentModel->where(['circle_id' => $info['id'], 'pid' => 0])
            ->limit($start, $limit)->count();
        $circleCommentLikeModel = new CircleCommentLike();
        if ($circleCommentList) {
            foreach ($circleCommentList as $key => $value) {
                $like = $circleCommentLikeModel->where(['comment_id' => $value['id'], 'uid' => $request->userInfo['id']])->find();
                if ($like) {
                    $circleCommentList[$key]['is_like'] = 1;
                } else {
                    $circleCommentList[$key]['is_like'] = 0;
                }
                $circleCommentList[$key]['son_comment'] = [];
                $sonComment = $circleCommentModel
                    ->alias('cc')->leftJoin('user u', 'cc.uid  = u.id')
                    ->leftJoin('user ru', 'cc.reply_uid  = ru.id')
                    ->field('cc.*,u.nickname,u.avatar,ru.nickname as ru_nickname,ru.avatar as ru_avatar')
                    ->where(['comment_id' => $value['id']])
                    ->limit(0, 2)->select()->toArray();
                if ($sonComment) {
                    foreach ($sonComment as $sonCommentKey => $sonCommentValue) {
                        $like = $circleCommentLikeModel->where(['comment_id' => $sonCommentValue['id'], 'uid' => $request->userInfo['id']])->find();
                        if ($like) {
                            $sonComment[$sonCommentKey]['is_like'] = 1;
                        } else {
                            $sonComment[$sonCommentKey]['is_like'] = 0;
                        }
                    }
                }
                $circleCommentList[$key]['son_comment'] = $sonComment;
            }
        }
        $info['comment'] = $circleCommentList;
        $info['comment_count'] = $count;
        return success('圈子详情', $info);

    }

    public function comment(Request $request)
    {
        $param = $request->param();
        $circleModel = new \app\common\model\Circle();
        $circleInfo = $circleModel->where(['id' => $param['id']])->find();
        if (empty($circleInfo)) {
            return error('圈子不存在');
        }
        $data = [
            'content' => $param['content'],
            'circle_id' => $param['id'],
            'pid' => 0,
            'uid' => $request->userInfo['id'],
            'reply_uid' => $circleInfo['uid'],
            'create_time' => time(),
        ];
        $circleCommentModel = new CircleComment();
        $circleModel->where(['id' => $param['id']])->inc('comment_number')->update();
        $circleCommentModel->insert($data);
        $noticeMessageModel = new  NoticeMessage();
        $noticeMessageModel->insert([
            'content' => $param['content'],
            'uid' => $request->userInfo['id'],
            'receive_uid' => $circleInfo['uid'],
            'type' => 1,
            'circle_id' => $param['id'],
            'create_time' => time(),
            'is_read' => 0,
            'update_time' => time(),
        ]);
        return success('评论成功');

    }

    public function replyComment(Request $request)
    {
        $param = $request->param();
        $circleCommentModel = new CircleComment();
        $circleCommentInfo = $circleCommentModel->where(['id' => $param['id']])->find();
        $data = [
            'content' => $param['content'],
            'circle_id' => $circleCommentInfo['circle_id'],
            'pid' => $param['id'],
            'uid' => $request->userInfo['id'],
            'reply_uid' => $circleCommentInfo['uid'],
            'create_time' => time(),
        ];
        if ($circleCommentInfo['pid'] == 0) {
            $data['comment_id'] = $param['id'];
        } else {
            $data['comment_id'] = $circleCommentInfo['comment_id'];
        }
        $circleCommentModel->where(['id' => $data['comment_id']])->inc('comment_number')->update();
        $circleCommentModel->insert($data);
        $noticeMessageModel = new  NoticeMessage();
        $noticeMessageModel->insert([
            'content' => $param['content'],
            'uid' => $request->userInfo['id'],
            'receive_uid' => $circleCommentInfo['uid'],
            'type' => 4,
            'circle_id' => $circleCommentInfo['circle_id'],
            'create_time' => time(),
            'is_read' => 0,
            'update_time' => time(),
        ]);
        return success('评论成功');

    }

    public function commentList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $circleCommentModel = new CircleComment();
        $circleCommentLikeModel = new CircleCommentLike();
        $circleCommentList = $circleCommentModel->alias('cc')
            ->leftJoin('user u', 'cc.uid  = u.id')
            ->where(['circle_id' => $param['id'], 'cc.pid' => 0])
            ->field('cc.*,u.nickname,u.avatar')
            ->order('create_time', 'desc')
            ->limit($start, $limit)->select()->toArray();
        $count = $circleCommentModel->where(['circle_id' => $param['id'], 'pid' => 0])
            ->limit($start, $limit)->count();
        if ($circleCommentList) {
            foreach ($circleCommentList as $key => $value) {
                $circleCommentList[$key]['son_comment'] = [];
                $circleCommentList[$key]['son_comment'] = $circleCommentModel->alias('cc')
                    ->leftJoin('user u', 'cc.uid  = u.id')
                    ->leftJoin('user ru', 'cc.reply_uid  = ru.id')
                    ->field('cc.*,u.nickname,u.avatar,ru.nickname as ru_nickname,ru.avatar as ru_avatar')
                    ->where(['cc.comment_id' => $value['id']])
                    ->limit(0, 2)->select()->toArray();
                $like = $circleCommentLikeModel->where(['comment_id' => $value['id'], 'uid' => $request->userInfo['id']])->find();
                if ($like) {
                    $circleCommentList[$key]['is_like'] = 1;
                } else {
                    $circleCommentList[$key]['is_like'] = 0;
                }
                if ($circleCommentList[$key]['son_comment']) {
                    foreach ($circleCommentList[$key]['son_comment'] as $sonCommentKey => $sonCommentValue) {
                        $like = $circleCommentLikeModel->where(['comment_id' => $sonCommentValue['id'], 'uid' => $request->userInfo['id']])->find();
                        if ($like) {
                            $circleCommentList[$key]['son_comment'][$sonCommentKey]['is_like'] = 1;
                        } else {
                            $circleCommentList[$key]['son_comment'][$sonCommentKey]['is_like'] = 0;
                        }
                    }
                }
            }
        }
        return success('圈子评论', ['list' => $circleCommentList, 'count' => $count]);

        /* if (isset($param['circle_id']) &&  )*/
    }

    public function replyCommentList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 2;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit + $start;
        }
        $circleCommentModel = new CircleComment();
        $circleCommentList = $circleCommentModel->alias('cc')
            ->leftJoin('user u', 'cc.uid  = u.id')
            ->leftJoin('user ru', 'cc.reply_uid  = ru.id')
            ->field('cc.*,u.nickname,u.avatar,ru.nickname as ru_nickname,ru.avatar as ru_avatar')
            ->where(['cc.comment_id' => $param['id']])
            ->limit($start, $limit)->select()->toArray();
        $circleCommentLikeModel = new CircleCommentLike();
        foreach ($circleCommentList as $key => $value) {
            $like = $circleCommentLikeModel->where(['comment_id' => $value['id'], 'uid' => $request->userInfo['id']])->find();
            if ($like) {
                $circleCommentList[$key]['is_like'] = 1;
            } else {
                $circleCommentList[$key]['is_like'] = 0;
            }
        }
        $count = $circleCommentModel->where(['comment_id' => $param['id']])->count();
        return success('圈子回复评论', ['list' => $circleCommentList, 'count' => $count]);
    }

    public function commentLike(Request $request)
    {
        $param = $request->param();
        $circleCommentLike = new CircleCommentLike();
        $circleCommentModel = new CircleComment();
        $noticeMessageModel = new  NoticeMessage();
        $circleCommentInfo = $circleCommentModel->where(['id' => $param['comment_id']])->find();
        $noticeMessageData = [
            'uid' => $request->userInfo['id'],
            'receive_uid' => $circleCommentInfo['uid'],
            'circle_id' => $circleCommentInfo['circle_id'],
            'comment_id' => $param['comment_id'],
        ];
        $noticeMessageinfo = $noticeMessageModel->where($noticeMessageData)->find();
        if ($param['is_like'] == 1) {
            $circleCommentLikeInfo = $circleCommentLike->where(['uid' => $request->userInfo['id'], 'comment_id' => $param['comment_id']])->find();
            if ($circleCommentLikeInfo) {
                return error('重复点赞');
            }
            $circleCommentLike->insert([
                'uid' => $request->userInfo['id'],
                'comment_id' => $param['comment_id'],
                'create_time' => time()
            ]);
            $circleCommentModel->where(['id' => $param['comment_id']])->inc('like_number')->update();
            if ($noticeMessageinfo) {
                $noticeMessageModel->where($noticeMessageData)->update(['is_read' => 0, 'update_time' => time(), 'type' => 5]);
            } else {
                $noticeMessageData['is_read'] = 0;
                $noticeMessageData['type'] = 5;
                $noticeMessageData['update_time'] = time();
                $noticeMessageData['create_time'] = time();

                $noticeMessageModel->insert($noticeMessageData);
            }
        } else {
            $circleCommentLikeInfo = $circleCommentLike->where([
                'uid' => $request->userInfo['id'],
                'comment_id' => $param['comment_id'],
            ])->find();
            if (empty($circleCommentLikeInfo)) {
                return error('已取消');
            }
            $circleCommentLike->where([
                'uid' => $request->userInfo['id'],
                'comment_id' => $param['comment_id'],
            ])->delete();
            $circleCommentModel->where(['id' => $param['comment_id']])->dec('like_number')->update();
            $noticeMessageModel->where($noticeMessageData)->update(['is_read' => 0, 'update_time' => time(), 'type' => 6]);
        }
        return success('操作成功');
    }

    public function circleLike(Request $request)
    {
        $param = $request->param();
        $circleLike = new CircleLike();
        $circleModel = new \app\common\model\Circle();
        $noticeMessageModel = new  NoticeMessage();
        $circleInfo = $circleModel->where(['id' => $param['id']])->find();
        $noticeMessageData = [
            'uid' => $request->userInfo['id'],
            'receive_uid' => $circleInfo['uid'],
            'circle_id' => $circleInfo['id'],
        ];
        $noticeMessageInfo = $noticeMessageModel->where($noticeMessageData)->find();
        if ($param['is_like'] == 1) {
            $circleLikeInfo = $circleLike->where([
                'uid' => $request->userInfo['id'],
                'circle_id' => $param['id'],
            ])->find();
            if ($circleLikeInfo) {
                return error('重复点赞');
            }
            $circleLike->insert([
                'uid' => $request->userInfo['id'],
                'circle_id' => $param['id'],
                'create_time' => time(),

            ]);
            $circleModel->where(['id' => $param['id']])->inc('like_number')->update();
            if ($noticeMessageInfo) {
                $noticeMessageModel->where($noticeMessageData)->update(['is_read' => 0, 'update_time' => time(), 'type' => 2]);
            } else {
                $noticeMessageData['is_read'] = 0;
                $noticeMessageData['type'] = 2;
                $noticeMessageData['update_time'] = time();
                $noticeMessageData['create_time'] = time();
                $noticeMessageModel->insert($noticeMessageData);
            }
        } else {
            $circleLikeInfo = $circleLike->where([
                'uid' => $request->userInfo['id'],
                'circle_id' => $param['id'],
            ])->find();
            if (empty($circleLikeInfo)) {
                return error('已取消');
            }
            $circleLike->where([
                'uid' => $request->userInfo['id'],
                'circle_id' => $param['id'],
            ])->delete();
            $circleModel->where(['id' => $param['id']])->dec('like_number')->update();
            $noticeMessageModel->where($noticeMessageData)->update(['is_read' => 0, 'update_time' => time(), 'type' => 3]);
        }
        return success('操作成功');
    }

    public function updateCircleStatus(Request $request)
    {
        $param = $request->param();
        $circleModel = new \app\common\model\Circle();
        $data['status'] = $param['status'];
        if (isset($param['remark']) && !empty($param['remark'])) {
            $data['remark'] = $param['remark'];
        }
        $circleModel->where(['id' => $param['id']])->update($data);


        return success('操作成功');
    }


}